package com.ego.search.listnener;

import com.ego.item.bo.SpuBo;
import com.ego.item.service.GoodsService;
import com.ego.search.client.GoodsClient;
import com.ego.search.pojo.Goods;
import com.ego.search.repository.GoodsRepository;
import com.ego.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.support.ElasticsearchEntityInformation;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GoodsListener {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private SearchService searchService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private GoodsClient goodsClient;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = "ego.item.exchange",//指定交换机
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC//消息模型
            ),
            value = @Queue(value = "ego.update.index.queue", durable = "true"
            ),//指定队列
            key = {"item.insert", "item.update"}//routingKey
    ))
    public void insertListener(Long id) throws IOException {
        if (id == null) {
            return;
        }
        //来创建索引.....更新索引...//es中id有的话好像可以直接更新得.
        SpuBo spuBo = this.goodsClient.queryGoodsById(id);
        //然后单独构建一个goods
        Goods goods = this.searchService.buildGoods(spuBo);
        //然后保存/更新到es
        this.goodsRepository.save(goods);
    }

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = "ego.item.exchange",//指定交换机
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC//消息模型
            ),
            value = @Queue(value = "ego.delete.index.queue", durable = "true"
            ),//指定队列
            key = {"item.delete"}//routingKey
    ))
    public void deleteListener(Long id) {
        if (id == null) {
            return;
        }
        this.goodsRepository.deleteById(id);
    }

}
